package mspbots.autotask.data.core.information;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import mspbots.autotask.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * mspbots.core.sync.autotask.badmessage.BadMessageReceiver
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/7/21
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class InformationReceiver extends AbstractToolsUtil {

    private final InformationRepository informationRepository;

    @RabbitListener(queues = "auto-task.entity-information.sync")
    public void syncTask(ResultMsg content) {

        Information information = Information.builder().name(content.getEntity().get("name").textValue())
                .type(content.getAction())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
                .entity(content.getEntity())
                .build();

        this.informationRepository.findByTenantIdAndTypeAndName(content.getTenantId(), content.getAction(), information.getName())
                .map(ticket -> {
                    information.setId(ticket.getId());
                    return information;
                })
                .defaultIfEmpty(information)
                .flatMap(this.informationRepository::save)
                .block(Duration.ofSeconds(10));

    }

}
